package com.xzx.study;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SharedPreferenceActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText shared_pre_key;
    private EditText shared_pre_value;
    private Button shared_pre_save;
    private Button shared_pre_read;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preference);

        shared_pre_key = findViewById(R.id.shared_pre_key);
        shared_pre_value = findViewById(R.id.shared_pre_value);
        shared_pre_save = findViewById(R.id.shared_pre_save);
        shared_pre_read = findViewById(R.id.shared_pre_read);

        shared_pre_save.setOnClickListener(this);
        shared_pre_read.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == shared_pre_save) {
            SharedPreferences sharedPreferences = getSharedPreferences("mysp", Context.MODE_PRIVATE);
            sharedPreferences.edit().putString(shared_pre_key.getText().toString(),
                                               shared_pre_value.getText().toString()).apply();
            Toast.makeText(this, "save 成功", Toast.LENGTH_SHORT).show();
        } else if(v == shared_pre_read) {
            SharedPreferences sharedPreferences = getSharedPreferences("mysp", Context.MODE_PRIVATE);
            String value = sharedPreferences.getString(shared_pre_key.getText().toString(), "key不存在");
            shared_pre_value.setText(value);

        }
    }
}
